package com.book.bookprojectapplication.login.activity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.book.bookprojectapplication.R;
import com.tistory.whdghks913.croutonhelper.CroutonHelper;

import de.keyboardsurfer.android.widget.crouton.Style;

public class LoginActivity extends Activity {

	JSONObject jArray;
	String urlpassword = "http://192.168.123.182:8090/test/csjemailpasswordcheck.do";

	Bundle extra = new Bundle();
	EditText emailText1, passwordText2;
	TextView textViewemail, textViewpassword;
	CroutonHelper mHelper;

	HttpResponse response;
	String inputdata;
	String results;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		Button startButton = (Button) findViewById(R.id.backmainBtn);

		emailText1 = (EditText) findViewById(R.id.emailText1);
		passwordText2 = (EditText) findViewById(R.id.passwordText2);

		startButton.setOnClickListener(new ImageButton.OnClickListener() {

			public void onClick(View v) {

				Intent myIntent = new Intent(getApplicationContext(),
						MainActivity.class);
				extra.putString("key", "ok");
				myIntent.putExtras(extra);
				startActivity(myIntent);

			}

		});

		Button loginBtn2 = (Button) findViewById(R.id.loginBtn2);

		loginBtn2.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {

				inputdata = "?memail1=" + emailText1.getText().toString()
						+ "&mpassword=" + passwordText2.getText().toString();
				System.out.println("inputdata is : " + inputdata);

				new LoginDownloadJSON().execute(urlpassword);

			}

		});

		textViewemail = (TextView) findViewById(R.id.textViewemail);
		textViewemail.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(getApplicationContext(),
						Findemail.class);
				startActivity(myIntent);

			}
		});

		textViewpassword = (TextView) findViewById(R.id.textViewpassword);
		textViewpassword.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(getApplicationContext(),
						Findpassword.class);
				startActivity(myIntent);

			}
		});
	}

	private class LoginDownloadJSON extends AsyncTask<String, Void, Void> {

		private String[] getJsonData = { "" };

		@Override
		protected Void doInBackground(String... urls) {

			System.out.println("doInBackground ()");
			InputStream is = null;
			results = "";
			String data = inputdata;
			
			// System.out.println("data is : " + inputdata);

			// Download JSON data from URL
			try {
				HttpClient httpclient = new DefaultHttpClient();
				HttpPost httppost = new HttpPost(urls[0] + data);
				response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();

				// Convert response to string

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is, "utf-8"), 8);
				StringBuilder sb = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
				is.close();
				results = sb.toString();
				System.out.println("result 값: " + results);
				jArray = new JSONObject(results);
				System.out.println("jArray 값: " + jArray);

				JSONArray resarray = jArray.getJSONArray("checkresult");
				for (int i = 0; i < resarray.length(); i++) {
					jArray = resarray.getJSONObject(i);
					getJsonData[0] = jArray.getString("res");
				}

			} catch (Exception e) {
				Log.e("log_tag", "Error converting result " + e.toString());
			}

			return null;

		}

		@Override
		protected void onPostExecute(Void args) {

			mHelper = new CroutonHelper(LoginActivity.this);
			mHelper.setDuration(1000);
			System.out.println("onPosetExecute ()");

			if (emailText1.getText().toString().equals("")
					&& passwordText2.getText().toString().equals("")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("이메일과 비밀번호를 입력해주세요");
				mHelper.show();

			} else if (emailText1.getText().toString().equals("")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("이메일을 입력해주세요");
				mHelper.show();

			} else if (passwordText2.getText().toString().equals("")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("비밀번호를 입력해주세요");
				mHelper.show();
			} else if (getJsonData[0].equals("no")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("이메일과 비밀번호를 확인해주세요");
				mHelper.show();

			} else if (getJsonData[0].equals("ok")) {
				Intent myIntent = new Intent(getApplicationContext(),
						WritingList.class);
				startActivity(myIntent);

			} else if (getJsonData[0].equals("noe")) {
				mHelper.setStyle(Style.ALERT);
				mHelper.setText("존재하지않는 이메일 입니다.");
				mHelper.show();

			}

		}

	}

}
